<?php

namespace app\common\library;

/**
 * 百家云
 */
class Baijia
{
    /**
     * 合作方partner_id
     */
    protected static $partner_id = "62523825";

    /**
     * 合作方partner_key
     */
    protected static $partner_key = "eOXw5jwrK+kGRH2LsIu4csg9Y0PrhC0TARormqEkApHCD9MaOGqkGTgl69uLxf8vkAf7zwZn90gOjyvwX7AoKcOg8IOCqZnQEI67hA56lElDirbus/oW2jnRxQKhfMsw";
    
    /**
     * 合作方secret_key
     */
    protected static $secret_key = "b62e600a15942505a27e39728bc3748d";

    /**
     * 百家云签名计算
     * @param array $params
     * @param string  $partner_key
     * @return string $gign
     */
    public static function getSign($params) {
        ksort($params);//将参数按key进行排序
        $str = '';
        foreach ($params as $k => $val) {
            $str .= "{$k}={$val}&"; //拼接成 key1=value1&key2=value2&...&keyN=valueN& 的形式
        }
        $str .= "partner_key=" . self::$partner_key; //结尾再拼上 partner_key=$partner_key
        $sign = md5($str); //计算md5值
        return $sign;
    }


    /**
     * 创建房间
     * @param int $startTime 开始时间
     * @param int $endTime 结束时间
     * @param string $title 课程标题
     * @param string $room_type 房间类型 large 大班课 small 小班课 1v1 专业1v1
     * @param string $max_users 房间最大进入人数
     * @param int $preEnterTime 可以提前进入教室时间
     * @param int  $delayTime 允许拖堂时间
     * @return array $res
     */
    public static function createRoom($startTime,$endTime,$title,$room_type,$max_users,$preEnterTime=900,$delayTime=1200)
    {

        
        if($room_type == 'large'){ //大班课
           
            $params =  [
                "partner_id" => self::$partner_id,  //合作方id
                "title" => $title,    //直播课标题
                "start_time" => $startTime, //开始时间  时间戳
                "type" => 2,                //1:一对一课 2:普通大班课 3:互动小班课 默认为普通大班课
                "end_time" => $endTime,   //结束时间  时间戳
                "pre_enter_time" => $preEnterTime,   //学生可提前进入的时间，单位为秒，默认为30分钟
                "max_users" => $max_users ? $max_users : 0,//代表普通大班课最大人数, 不传或传0表示不限制
                //  （注：需要给账号开通长期房间权限才可以创建长期房间）
                "push_live_record" => 1,  //推流直播自动录制 1：是，0：否
                "end_delay_time" => $delayTime,
                "timestamp" => time(),         //当前时间戳  
            ];
        }else{ //小班课 分为基础1v1 和专业 1v1
            $params =  [
                "partner_id" => self::$partner_id,  //合作方id
                "title" => $title,    //直播课标题
                "start_time" =>$startTime, //开始时间  时间戳
                "type" => $room_type == 'small' ? 6 : 4,  //4:专业一对一；6：基础班一对一
                "max_users" => $room_type == '1v1'? 1 : 2,
                "end_time" => $endTime,   //结束时间  时间戳
                "pre_enter_time" => $preEnterTime,   //学生可提前进入的时间，单位为秒，默认为30分钟
                //  （注：需要给账号开通长期房间权限才可以创建长期房间）
                "template_type"=> 1,         //可选值：小班课模板类型 可传1,2,3；1为第一套模板；2为第二套模板；3为一对一模板，需申请开通
                "auto_playback_record" => 1,  //自动开启云端录制，1:允许,0:取账号配置,如果隐藏了云端录制按钮，则不会自动开启
                "end_delay_time" => $delayTime,
                "timestamp" => time(),         //当前时间戳  
            ];
        }
        $params['sign'] = self::getSign($params);

        $url = "https://b62523825.at.baijiayun.com/openapi/room/create";
        $request = self::http_request($url,$params);  
        $res = json_decode($request,true);
    	return $res;
    }

    /**
     * 更新房间
     * @param int $room_id 房间号
     * @param int $startTime 开始时间
     * @param int $endTime 结束时间
     * @param string $title 课程标题
     * @param string $room_type 房间类型 large 大班课 small 小班课 1v1 专业1v1
     * @param string $max_users 房间最大进入人数
     * @param int $preEnterTime 可以提前进入教室时间
     * @param int  $delayTime 允许拖堂时间
     * @return array $res
     */
    public static function updateRoom($room_id,$startTime,$endTime,$title,$room_type,$max_users,$preEnterTime=900,$delayTime=1200)
    {

        
        if($room_type == 'large'){ //大班课
            $params =  [
                "partner_id" => self::$partner_id,  //合作方id
                "room_id"   => $room_id,
                "title" => $title,    //直播课标题
                "start_time" => $startTime, //开始时间  时间戳
                "type" => 2,                //1:一对一课 2:普通大班课 3:互动小班课 默认为普通大班课
                "end_time" => $endTime,   //结束时间  时间戳
                "pre_enter_time" => $preEnterTime,   //学生可提前进入的时间，单位为秒，默认为30分钟
                "max_users" => $max_users ? $max_users : 0,//代表普通大班课最大人数, 不传或传0表示不限制
                //  （注：需要给账号开通长期房间权限才可以创建长期房间）
                "push_live_record" => 1,  //推流直播自动录制 1：是，0：否
                "end_delay_time" => $delayTime,
                "timestamp" => time(),         //当前时间戳  
            ];
        }else{ //小班课 分为基础1v1 和专业 1v1
            $params =  [
                "partner_id" => self::$partner_id,  //合作方id
                "room_id"   => $room_id,
                "title" => $title,    //直播课标题
                "start_time" =>$startTime, //开始时间  时间戳
                "type" => $room_type == 'small' ? 6 : 4,  //4:专业一对一；6：基础班一对一
                "max_users" => $room_type == '1v1'? 1 : 2,
                "end_time" => $endTime,   //结束时间  时间戳
                "pre_enter_time" => $preEnterTime,   //学生可提前进入的时间，单位为秒，默认为30分钟
                //  （注：需要给账号开通长期房间权限才可以创建长期房间）
                "template_type"=> 1,         //可选值：小班课模板类型 可传1,2,3；1为第一套模板；2为第二套模板；3为一对一模板，需申请开通
                "auto_playback_record" => 1,  //自动开启云端录制，1:允许,0:取账号配置,如果隐藏了云端录制按钮，则不会自动开启
                "end_delay_time" => $delayTime,
                "timestamp" => time(),         //当前时间戳  
            ];
        }
 
       
        $params['sign'] = self::getSign($params);

        $url = "https://b62523825.at.baijiayun.com/openapi/room/update";
        $request = self::http_request($url,$params);  
        $res = json_decode($request,true);
    	return $res;
    }

    /**
     * 设置视频公告
     * @param string  $notice 公告参数
     * @return string $url
     */
    public static function setRollNotice($notice)
    {
        $params =  [
            "partner_id" => self::$partner_id,  //合作方id
            "notice" => $notice,    
            "timestamp" => time(),
        ];
        $params['sign'] = self::getSign($params);
        $url = "https://b62523825.at.baijiayun.com/openapi/notice/setRollNotice";
        $request = self::http_request($url,$params);  
        $res = json_decode($request,true);
    	return $res;
    }


    /**
     * 生成直播间链接
     * @param string  $room_id 房间id
     * @param string  $username 用户名
     * @param string  $user_id 用户id
     * @param int  $role 用户角色 0:学生 1:老师 2:管理员 
     * @return string $url
     */
    public static function liveRoomUrl($room_id,$username,$user_id,$role = 0)
    {
        $params =  [
            "room_id" => $room_id,  
            "user_number" => $user_id,    
            "user_role" => $role, //0:学生 1:老师 2:管理员0:学生 1:老师 2:管理员
            "user_name" => $username,  
        ];
        $params['sign'] = self::getSign($params);

        $url = 'https://b62523825.at.baijiayun.com/web/room/enter?room_id='.$params['room_id'].'&user_number='.$params['user_number'].'&user_name='.urlencode($params['user_name']).'&user_role='.$params['user_role'].'&sign='.$params['sign'];
        return $url;
    }

    /**
     * 生成直播间链接
     * @param string  $room_id 房间id
     * @param string  $room_type 房间类型
     * @return array $res
     */
    public static function getReplay($room_id,$room_type)
    {
        $params =  [
            "partner_id" => self::$partner_id,  //合作方id
            "product_type" => $room_type == 'large' ? 1 : 2,    //1:教育直播，2，小班课，3：双师，4，企业直播
            "page" => 1, //页码
            "page_size" => 10, //每页显示条数
            "room_id" => $room_id,   //房间号
            "timestamp" => time(),  //当前时间戳  
        ];
 
        // 生成sign
        $params['sign'] = self::getSign($params);
        $url = "https://b62523825.at.baijiayun.com/openapi/playback/getList";
        $request = self::http_request($url,$params); 
        $res = json_decode($request,true);
        
    	return $res;
    }

    /**
     * 点播课上传地址获取
     * @param string  $filename 文件名
     * @param string  $definition 清晰度 16:标清 1:高清 2:超清 4:720p 8:1080p 
     * @return array $res
     */
    public static function getUploadUrl($filename,$definition=16)
    {
        $params =  [
            "partner_id" => self::$partner_id,  
            "file_name" => $filename,    
            "definition" => $definition, 
            "timestamp" => time(), 
        ];

        $params['sign'] = self::getSign($params);

        $url = "https://b62523825.at.baijiayun.com/openapi/video/getUploadUrl";
        $request = self::http_request($url,$params);  
        $res = json_decode($request,true);
    	return $res;
    }

    /**
     * 点播课文件上传
     * @param string  $fid 文件fid
     * @return string $url
     */
    public static function upload($fid)
    {
        $params = [
            'fid' => $fid,
            'ts' => time()
        ];

        $params['sign'] = self::getSign($params);

        $url = "http://upload-video.baijiayun.com/upload?fid=".$params['fid']."&ts=".$params['ts']."token=".$params['sign'];
        return $url;
    }

    /**
     * 获取视频点播token
     * @param string  $video_id 视频id
     * @return string $res
     */
    public static function getPlayerToken($video_id)
    {
        $params =  [
            "partner_id" => self::$partner_id,  
            "video_id" => $video_id,    
            "timestamp" => time(), 
        ];

        $params['sign'] = self::getSign($params);

        $url = "https://b62523825.at.baijiayun.com/openapi/video/getPlayerToken";
        $request = self::http_request($url,$params);  
        $res = json_decode($request,true);
    	return $res;
    }

    /**
     * 获取视频点播token
     * @param string  $room_id 直播间id
     * @return string $res
     */
    public static function getReplayToken($room_id)
    {
        $params =  [
            "partner_id" => self::$partner_id,  
            "room_id" => $room_id,  
            "expires_in" => 0,
            "timestamp" => time(), 
        ];

        $params['sign'] = self::getSign($params);

        $url = "https://b62523825.at.baijiayun.com/openapi/playback/getPlayerToken";
        $request = self::http_request($url,$params);  
        $res = json_decode($request,true);
    	return $res;
    }

    /**
     * 获取视频点播封面
     * @param string  $video_id 视频id
     * @return string $res
     */
    public static function getVideoCover($video_id)
    {
        $params =  [
            "partner_id" => self::$partner_id,  
            "video_id" => $video_id,    
            "timestamp" => time(), 
        ];

        $params['sign'] = self::getSign($params);

        $url = "https://b62523825.at.baijiayun.com/openapi/video/getImage";
        $request = self::http_request($url,$params);  
        $res = json_decode($request,true);
    	return $res;
    }

    /**
     * 设置转码回调地址
     * @param string  $url 地址
     * @return string $res
     */
    public static function setTranscodeCallbackUrl($url)
    {
        $params =  [
            "partner_id" => self::$partner_id,  
            "url" => $url,    
            "timestamp" => time(), 
        ];
        $params['sign'] = self::getSign($params);
        $url = "https://b62523825.at.baijiayun.com/openapi/video_account/setTranscodeCallbackUrl";
        $request = self::http_request($url,$params);  
        $res = json_decode($request,true);
    	return $res;
    }

    /**
     * 设置上下课回调地址
     * @param string  $url 地址
     * @return string $res
     */
    public static function setClassCallbackUrl($url)
    {
        $params =  [
            "partner_id" => self::$partner_id,  
            "url" => $url,    
            "timestamp" => time(), 
        ];
        $params['sign'] = self::getSign($params);
        $url = "https://b62523825.at.baijiayun.com/openapi/live_account/setClassCallbackUrl";
        $request = self::http_request($url,$params);  
        $res = json_decode($request,true);
    	return $res;
    }



    /**
     * curl封装
     * @param string $url
     * @param array  $arr
     * @return mixed $ret
     */
    public static function http_request($url,$arr)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$arr);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);;
        //执行并获取接口传的内容
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }

}
